package com.baizhi.reflect2;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * 通过反射获取成员变量,并使用成员变量
 */
public class FieldDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException, InstantiationException, IllegalAccessException {

        //通过new关键字创建对象 ,不能访问私有属性，不能访问私有方法
       // Person p = new Person();
       // p.name = "张三";
        //p.address = "北京";

        //1. 获取Class对象
        Class<Person> pCass = Person.class;

        //2.获取构造函数
        Constructor<Person> con = pCass.getConstructor(String.class, int.class, String.class);

        //3. 创建Person对象
        Person person = con.newInstance("王云爽", 17, "北京市海淀区");

        //4. 获取指定的成员变量
        String name = person.name; //可以直接获取
        int age = person.age; //可以直接获取
        //address 被private修饰不能直接获取，可以通过反射获取
        Field address = pCass.getDeclaredField("address");
        //取消Java语言提供的private权限
        address.setAccessible(true);

        Object o = address.get(person); //获取私有属性address
        System.out.println("o="+o);

        System.out.println("name:"+name + ",age:"+age);


        //5. 通过方法，给定制的成员变量赋值，或者使用
        //改变属性的值
        person.name = "赵云不爽";
        person.age = 75;
        address.set(person,"河北石家庄");

        o = address.get(person);


        System.out.println("name:"+person.name + ",age:"+person.age+"，address:"+o);

    }
}
